<template>
  <div class="mission-container">
    <div class="mission-content">
      <!-- 查询条件 -->
      <t-form
        ref="form"
        :data="queryParams"
        label-width="80px"
        layout="inline"
        class="search-form"
        colon
      >
        <t-row style="width: 100%">
          <t-col :span="3">
            <t-form-item label="任务名称">
              <t-input
                v-model="queryParams.name"
                placeholder="请输入任务名称"
                clearable
                style="width: 158px"
              />
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item label="任务类型">
              <t-select
                v-model="queryParams.type"
                placeholder="请选择类型"
                clearable
                style="width: 158px"
              >
                <t-option
                  v-for="(label, value) in MissionTypeLabels"
                  :key="value"
                  :value="value"
                  :label="label"
                >
                  {{ label }}
                </t-option>
              </t-select>
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-form-item>
              <t-space>
                <t-button theme="primary" @click="handleSearch"> 查询 </t-button>
                <t-button theme="default" @click="handleReset"> 重置 </t-button>
              </t-space>
            </t-form-item>
          </t-col>

          <t-col :span="3">
            <t-row justify="end">
              <t-button theme="primary" variant="base" @click="handleAdd">
                <template #icon>
                  <t-icon name="add" />
                </template>
                新增任务
              </t-button>
            </t-row>
          </t-col>
        </t-row>
      </t-form>

      <!-- 任务列表表格 -->
      <div class="mission-table">
        <t-table
          row-key="id"
          bordered
          height="calc(100vh - 55px - 28px - 28px - 16px - 64px - 70px)"
          :data="missionList"
          :columns="columns"
          :loading="loading"
          :pagination="pagination"
          @page-change="onPageChange"
        >
          <!-- 类型列 -->
          <template #missionType="{ row }">
            <t-tag theme="default">
              {{ MissionTypeLabels[row.missionType] || row.missionType }}
            </t-tag>
          </template>

          <!-- 积分奖励列 -->
          <template #points="{ row }">
            <span class="points-text">{{ row.points }} 积分</span>
          </template>

          <!-- 操作列 -->
          <template #op="{ row }">
            <div style="display: flex">
              <!-- <t-button theme="primary" variant="text" @click="handleView(row)"> 查看 </t-button> -->
              <t-button theme="success" variant="text" @click="handleEdit(row)"> 编辑 </t-button>
              <t-button theme="danger" variant="text" @click="handleDelete(row)"> 删除 </t-button>
            </div>
          </template>
        </t-table>
      </div>
    </div>

    <!-- 新增任务抽屉 -->
    <AddMissionDrawer v-model="addDrawerVisible" @success="handleAddSuccess" />

    <!-- 编辑任务抽屉 -->
    <AddMissionDrawer
      v-model="editDrawerVisible"
      :edit-data="currentEditData"
      :is-edit="true"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import { MessagePlugin, DialogPlugin as TDialog } from 'tdesign-vue';
import AddMissionDrawer from './components/add-mission-drawer.vue';
import { getMissionPage, deleteMission, updateMission } from '@/api/mission';

// 任务类型枚举
const MissionType = {
  CATALOG: 'CATALOG',    // 目录
  RECOMMEND: 'RECOMMEND', // 推荐
  EXAM: 'EXAM',         // 考试
  QNAIRE: 'QNAIRE',     // 问卷
};

// 任务类型标签
const MissionTypeLabels = {
  [MissionType.CATALOG]: '目录知识',
  [MissionType.RECOMMEND]: '推荐知识',
  [MissionType.EXAM]: '答题考试',
  [MissionType.QNAIRE]: '问卷调查',
};

export default {
  name: 'MissionList',
  components: {
    AddMissionDrawer,
  },
  data() {
    return {
      loading: false,
      missionList: [],
      MissionType,
      MissionTypeLabels,
      addDrawerVisible: false,
      editDrawerVisible: false,
      currentEditData: null,

      // 查询参数
      queryParams: {
        name: '',
        type: null,
      },

      // 表格列配置
      columns: [
        { colKey: 'name', title: '任务名称', width: 200, ellipsis: true },
        { colKey: 'description', title: '任务描述', ellipsis: true },
        { colKey: 'missionType', title: '任务类型', width: 120, align: 'center' },
        { colKey: 'points', title: '积分奖励', width: 120, align: 'center' },
        { colKey: 'createdAt', title: '创建时间', width: 180 },
        { colKey: 'op', title: '操作', width: 120, fixed: 'right' },
      ],

      // 分页配置
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showJumper: true,
        showPageSize: true,
        pageSizeOptions: [10, 20, 50, 100],
      },
    };
  },

  mounted() {
    this.loadMissionList();
  },

  methods: {
    // 加载任务列表
    async loadMissionList() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.queryParams,
        };

        // 清理空值参数
        Object.keys(params).forEach((key) => {
          if (params[key] === '' || params[key] === null) {
            delete params[key];
          }
        });

        const response = await getMissionPage(params);

        // 处理返回数据
        if (response && response.data && response.data.data) {
          this.missionList = Array.isArray(response.data.data.data) ? response.data.data.data : [];
          this.pagination.total = Number(response.data.data.total) || 0;
          this.pagination.current = Number(response.data.data.page) || this.pagination.current;
          this.pagination.pageSize = Number(response.data.data.pageSize) || this.pagination.pageSize;
        } else {
          this.missionList = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        console.error('加载任务列表失败:', error);
        MessagePlugin.error('加载任务列表失败');
        this.missionList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1;
      this.loadMissionList();
    },

    // 重置查询条件
    handleReset() {
      this.queryParams = {
        name: '',
        type: null,
      };
      this.pagination.current = 1;
      this.loadMissionList();
    },

    // 分页变化
    onPageChange({ current, pageSize }) {
      this.pagination.current = current;

      if (pageSize !== this.pagination.pageSize) {
        this.pagination.current = 1;
      }

      this.pagination.pageSize = pageSize;
      this.loadMissionList();
    },

    // 新增任务
    handleAdd() {
      console.log('handleAdd 方法被调用');
      console.log('设置前 addDrawerVisible:', this.addDrawerVisible);
      this.addDrawerVisible = true;
      console.log('设置后 addDrawerVisible:', this.addDrawerVisible);
    },

    // 新增任务成功回调
    handleAddSuccess() {
      this.loadMissionList();
    },

    // 查看任务
    handleView(row) {
      MessagePlugin.info(`查看任务: ${row.name}`);
    },

    // 编辑任务
    handleEdit(row) {
      this.currentEditData = { ...row };
      this.editDrawerVisible = true;
    },

    // 编辑任务成功回调
    handleEditSuccess() {
      this.loadMissionList();
    },

    // 删除任务
    async handleDelete(row) {
      if (!row || !row.id) {
        MessagePlugin.error('无效的数据');
        return;
      }

      const confirmMessage = `确定要删除任务"${row.name}"吗？`;
      const warningMessage = '删除后不可恢复。';

      try {
        const confirmDialog = await new Promise((resolve) => {
          const instance = TDialog.confirm({
            header: '确认删除',
            body: () => {
              return this.$createElement(
                'div',
                {
                  style: {
                    lineHeight: '1.6',
                  },
                },
                [
                  this.$createElement(
                    'p',
                    {
                      style: {
                        margin: '0 0 8px 0',
                        color: '#333',
                      },
                    },
                    confirmMessage
                  ),
                  this.$createElement(
                    'p',
                    {
                      style: {
                        margin: '0',
                        color: '#ff4d4f',
                        fontWeight: '500',
                      },
                    },
                    warningMessage
                  ),
                ]
              );
            },
            confirmBtn: {
              content: '确定删除',
              theme: 'danger',
              loading: false,
            },
            cancelBtn: '取消',
            onConfirm: () => {
              resolve(instance);
            },
            onCancel: () => {
              resolve(null);
            },
          });
        });

        if (!confirmDialog) {
          return;
        }

        confirmDialog.update({
          confirmBtn: {
            content: '删除中...',
            theme: 'danger',
            loading: true,
          },
        });

        // 调用删除API
        const res = await deleteMission(row.id);

        confirmDialog.hide();

        // 根据返回结果判断是否成功
        if (res && (res.code === 200 || res.data?.code === 200)) {
          MessagePlugin.success('删除成功');
          await this.loadMissionList();
        } else {
          throw new Error(res?.message || res?.data?.message || '删除失败');
        }
      } catch (error) {
        console.error('删除任务失败:', error);
        MessagePlugin.error(error.message || '删除任务失败');
      }
    },
  },
};
</script>

<style lang="less" scoped>
.mission-container {
  padding: 16px;
  background: #fff;
}

.mission-content {
  .search-form {
    background: #f8f9fa;
    padding: 16px;
    border-radius: 6px;
    margin-bottom: 16px;
  }

  .mission-table {
    background: #fff;
    border-radius: 6px;
  }

  .points-text {
    color: #f56c6c;
    font-weight: 500;
  }
}
</style>
